<template>
  <div id="app" @click="clickDiv">
    <n-message-provider>
      <Header></Header>
      <router-view />
      <Footer></Footer>
    </n-message-provider>
  </div>
</template>
<script>
import Header from "@/components/Header";
import { reactive, toRefs, watch } from "vue";
import { useRouter } from "vue-router";
import Footer from "@/components/Footer";
import { Toast } from "vant";
export default {
  components: {
    Footer,
    Header,
  },
  setup() {
    const state = reactive({
      lastTime: null, // 最后一次点击的时间
      currentTime: null, // 当前点击的时间
      timeOut: 10 * 60 * 1000, // 设置超时时间:10分钟
      timeInterval: "",
      name: "",
    });
    state.lastTime = new Date().getTime();
    const router = useRouter();
    const clickDiv = () => {
      if (state.timeInterval == "") {
        // 5秒钟检测一次
        state.timeInterval = setInterval(isTimeOut, 5000);
      }
      state.lastTime = new Date().getTime();
    };
    const isTimeOut = () => {
      state.currentTime = new Date().getTime(); // 当前时间
      // 判断上次最后一次点击的时间和这次点击的时间间隔是否大于规定的时间,例:10分钟
      if (state.currentTime - state.lastTime > state.timeOut) {
        //判断是否为登录状态,只有登录状态下才调用方法
        if (state.name != "Home") {
          clearInterval(state.timeInterval);
          state.timeInterval = "";
          router.push("/");
          Toast.fail({
            message: "由于长时间未操作，页面返回到首页",
            duration: 5000,
            overlay: true,
            closeOnClickOverlay: true,
            closeOnClick: true,
          });
          //先返回首页,在给提示,可以根据具体需求调整
        }
      }
    };
    watch(
      () => router.currentRoute.value,
      (val) => {
        state.name = val.name;
      }
    );
    return {
      clickDiv,
      ...toRefs(state),
    };
  },
};
</script>
<style lang="scss">
html,
body,
#app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
</style>
